﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Security.Cryptography;
using System.Globalization;

namespace NWBA_Public
{
    public class LoginUpdate
    {
        public static SqlConnection con = new SqlConnection(ServerString.getServerString());
        public LoginUpdate()
        {

        }
        public static Boolean updatePassword(string id, string password)
        {
            password = HashPassword(id,password);

            try
            {              
                con.Open();
                SqlCommand command = new SqlCommand("UPDATE [login] set Password=@password, ModifyDate=@date WHERE UserID=@id", con);
                command.Parameters.AddWithValue("@password", password);
                command.Parameters.AddWithValue("@date", DateTime.Now);
                command.Parameters.AddWithValue("@id", SqlDbType.NVarChar).Value=id;
                command.ExecuteScalar();
                return true;
            }
            catch (Exception o)
            {
                return false;
            }
            finally
            {
                con.Close();
            }
        }
        public static Login getLogin(string id)
        {
            SqlCommand command = new SqlCommand("SELECT * FROM [login] WHERE UserID=@id", con);
            command.Parameters.AddWithValue("@id", id);
            try
            {
                con.Open();
                SqlDataReader sqlr = command.ExecuteReader();
                while (sqlr.Read())
                {
                    Login newLogin = new Login();
                    newLogin.CustomerID = sqlr.GetInt32(0);
                    newLogin.UserID = sqlr.GetString(1);
                    newLogin.Password = sqlr.GetString(2);
                    return newLogin;
                }
                return null;
            }
            catch (Exception)
            {
                return null;
            }
            finally
            {
                con.Close();
            }
        }
        public static string HashPassword(string id, string password)
        {
            Login newLogin = LoginUpdate.getLogin(id);
            if (newLogin != null)
            {
                var passBytes = Encoding.Unicode.GetBytes(password);
                byte[] saltBytes = Encoding.Unicode.GetBytes(id);
                byte[] bytes = passBytes.Concat(saltBytes).ToArray();
                HashAlgorithm hash = HashAlgorithm.Create("MD5");
                byte[] pass = hash.ComputeHash(bytes);
                return Convert.ToBase64String(pass);
            }
            return null;
        }
    }
}